#pragma once

#include "data_def.h"
#include <thread>
#include <iostream>
#include <stdio.h>
#include <string>
#include <memory>
#include <atomic>

#include <boost/signals2.hpp>

extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/imgutils.h"
#include "libavfilter/avfilter.h"
};


class Rtsp2RtmpImpl
{
public:
    Rtsp2RtmpImpl(const Rtsp2RtmpReq_t& req, int rtmpMode);
    ~Rtsp2RtmpImpl();
    void start();
    int setPlayCount(bool isPlay);
    bool getRtsp2RtmpFlag();
    void setRtsp2RtmpFlag(bool flag);

private:
    void init();
    void unInit();

    int openInputByTcp(const std::string& inputUrl);
    int openInputByUdp(const std::string& inputUrl);
    int openOutput(const std::string& outUrl);

    std::shared_ptr<AVPacket> readPacketFromSourceByTcp();
    std::shared_ptr<AVPacket> readPacketFromSourceByUdp();
    int writePacket(std::shared_ptr<AVPacket> packet);
    
    void av_packet_rescale_ts(AVPacket *pkt, AVRational src_tb, AVRational dst_tb);

public:
    boost::signals2::signal<void(std::string)> _uninitSignal;

private:
    AVFormatContext* _inputContextTcp = nullptr;
    AVFormatContext* _inputContextUdp = nullptr;
    AVFormatContext* _outputContext = nullptr;

    std::atomic<bool> _isWorking;
    std::atomic<bool> _isInited;
    std::atomic<int> _playCount;

    std::string _node;
    std::string _inputUrl;
    std::string _outUrl;
    int _rtmpMode;
};